import tkinter as tk
from tkinter import messagebox, filedialog, ttk
import requests
import json
import os
import re

# 创建主窗口
root = tk.Tk()
root.title("MONSTER SIREN 音乐下载器")
root.geometry("800x600")
root.resizable(False, False)
root.configure(bg="#f0f0f0")

# 定义全局变量
songs_list = []
selected_song = None

# 定义函数
def msr_json(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            with open("msr.json", "w", encoding="utf-8") as file:
                json.dump(data, file, ensure_ascii=False, indent=4)
            messagebox.showinfo("成功", "JSON 数据已成功写入 msr.json 文件")
            load_songs()
        else:
            messagebox.showerror("失败", f"请求失败，状态码：{response.status_code}")
    except Exception as e:
        messagebox.showerror("错误", f"发生错误：{e}")

def load_songs():
    global songs_list
    try:
        with open("msr.json", "r", encoding="utf-8") as file:
            data = json.load(file)
            songs_list = data["data"]["list"]
            song_listbox.delete(0, tk.END)
            for song in songs_list:
                song_listbox.insert(tk.END, song["name"])
    except Exception as e:
        messagebox.showerror("错误", f"发生错误：{e}")

def search_songs():
    search_query = search_entry.get().lower()
    song_listbox.delete(0, tk.END)
    for song in songs_list:
        if search_query in song["name"].lower():
            song_listbox.insert(tk.END, song["name"])

def get_message():
    global selected_song
    selected_index = song_listbox.curselection()
    if selected_index:
        selected_song = songs_list[selected_index[0]]
        song_info_label.config(text=f"CID: {selected_song['cid']}\n名称: {selected_song['name']}\n作者: {', '.join(selected_song['artists'])}\n专辑CID: {selected_song['albumCid']}")
    else:
        messagebox.showwarning("警告", "请选择一首歌曲")

def get_path():
    path = filedialog.askdirectory()
    if path:
        path_entry.delete(0, tk.END)
        path_entry.insert(tk.END, path)

def get_down_url(html_url):
    try:
        response = requests.get(html_url)
        if response.status_code == 200:
            html = response.text
            pattern = r'"sourceUrl":"([^"]+\.\w+)"'
            matchs = re.findall(pattern, html)
            encoded_string = matchs[0]
            decoded_string = encoded_string.replace("\\\\", "/")
            decoded_string = decoded_string.replace("\\u002F", "/")
            return decoded_string
        else:
            messagebox.showerror("失败", f"请求失败，状态码：{response.status_code}")
    except Exception as e:
        messagebox.showerror("错误", f"发生错误：{e}")

def download_music(url, save_path):
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()
        total_size = int(response.headers.get('content-length', 0))
        block_size = 8192
        progress_bar['maximum'] = total_size
        progress_bar['value'] = 0
        with open(save_path, "wb") as file:
            for chunk in response.iter_content(chunk_size=block_size):
                file.write(chunk)
                progress_bar['value'] += len(chunk)
                root.update_idletasks()
        progress_bar['value'] = 0
        messagebox.showinfo("成功", f"文件已成功下载并保存到 {save_path}")
    except Exception as e:
        messagebox.showerror("错误", f"发生错误：{e}")

def download():
    if selected_song:
        cid = selected_song["cid"]
        html_url = f"https://monster-siren.hypergryph.com/music/{cid}"
        down_url = get_down_url(html_url)
        if down_url:
            save_path = os.path.join(path_entry.get(), f"{selected_song['name']}.mp3")
            download_music(down_url, save_path)
    else:
        messagebox.showwarning("警告", "请选择一首歌曲")

# 创建控件
title_label = tk.Label(root, text="MONSTER SIREN 音乐下载器", font=("微软雅黑", 20), bg="#f0f0f0")
title_label.pack(pady=20)

search_frame = tk.Frame(root, bg="#f0f0f0")
search_frame.pack(pady=10)

search_entry = tk.Entry(search_frame, width=50, font=("微软雅黑", 12))
search_entry.pack(side=tk.LEFT, padx=10)

search_button = tk.Button(search_frame, text="搜索", font=("微软雅黑", 12), command=search_songs)
search_button.pack(side=tk.LEFT, padx=10)

song_listbox = tk.Listbox(root, width=50, height=20, font=("微软雅黑", 12), selectmode=tk.SINGLE)
song_listbox.pack(side=tk.LEFT, padx=20, pady=20)

song_info_label = tk.Label(root, text="", font=("微软雅黑", 12), bg="#f0f0f0", justify=tk.LEFT)
song_info_label.pack(side=tk.TOP, padx=20, pady=20)

path_label = tk.Label(root, text="下载路径:", font=("微软雅黑", 12), bg="#f0f0f0")
path_label.pack(side=tk.TOP, padx=20)

path_entry = tk.Entry(root, width=50, font=("微软雅黑", 12))
path_entry.pack(side=tk.TOP, padx=20)

browse_button = tk.Button(root, text="浏览", font=("微软雅黑", 12), command=get_path)
browse_button.pack(side=tk.TOP, padx=20, pady=10)

download_button = tk.Button(root, text="下载", font=("微软雅黑", 12), command=download)
download_button.pack(side=tk.BOTTOM, padx=20, pady=20)

# 加载歌曲列表
load_button = tk.Button(root, text="加载歌曲列表", font=("微软雅黑", 12), command=lambda: msr_json("https://monster-siren.hypergryph.com/api/songs"))
load_button.pack(side=tk.BOTTOM, padx=20, pady=10)

# 选择歌曲
select_button = tk.Button(root, text="选择歌曲", font=("微软雅黑", 12), command=get_message)
select_button.pack(side=tk.BOTTOM, padx=20, pady=10)

# 添加进度条
progress_bar = ttk.Progressbar(root, orient="horizontal", length=400, mode="determinate")
progress_bar.pack(side=tk.BOTTOM, padx=20, pady=10)

# 运行主循环
root.mainloop()